package com.heima.schedule.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.common.constants.ScheduleConstants;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    /**
     * 添加延迟任务
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {
        // 1.添加任务到数据库中
        boolean success= addTaskToDB(task);
        // 2.添加任务到redis中
        if(success){
            addTaskToRedis(task);
        }
        return task.getTaskId();
    }

    @Autowired
    private RedisCacheService cacheService;
    /**
     * 添加任务到redis中
     * @param task
     */
    private void addTaskToRedis(Task task) {
        String key = task.getTaskType()+"_"+task.getPriority();
        // 获取预设时间，5分钟后
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long nextSchedule = calendar.getTimeInMillis();
        // 2.1 如果任务的执行时间小于当前时间，直接执行任务
        if(task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }
        // 2.2 如果任务的执行时间大于当前时间&&小于等于预设时间，添加到延迟队列中
        else if(task.getExecuteTime()>System.currentTimeMillis()&&task.getExecuteTime()<=nextSchedule){
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }
    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    /**
     * 添加任务到数据库中
     * @param task
     * @return
     */
    private boolean addTaskToDB(Task task) {
        boolean flag = false;
        try {
            // 1.保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            // 设置Task的id
            task.setTaskId(taskinfo.getTaskId());
            // 2.保存任务日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (Exception e) {
            log.error("添加任务到数据库失败",e);
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 删除任务
     * @param taskId
     * @return
     */
    @Override
    public boolean deleteTask(Long taskId) {
        boolean flag = false;
        //1.删除数据库中的任务
        int success = taskinfoMapper.deleteById(taskId);
        if(success==0){
            return flag;
        }
        try {
            //2.更新日志状态
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(ScheduleConstants.CANCELLED);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            //3.删除redis中的任务
            Task task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
            String key = task.getTaskType()+"_"+task.getPriority();
            if(task.getExecuteTime()<=System.currentTimeMillis()) {
                cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
            }else{
                cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
            }
            flag = true;
        } catch (Exception e) {
            log.error("删除任务失败",e);
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 按照类型和优先级拉取任务
     * @return
     */
    @Override
    public Task poll(int type,int priority) {
        Task task = null;
        try {
            String key = type+"_"+priority;
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if(StringUtils.isNotBlank(task_json)){
                task = JSON.parseObject(task_json, Task.class);
                //更新数据库信息
                taskinfoLogsMapper.updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("poll task exception");
        }

        return task;
    }


}
